package com.qmhl.toolposition.activity

import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.os.CountDownTimer
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.hjq.toast.Toaster
import com.qmhl.toolposition.R
import com.qmhl.toolposition.api.UserService
import com.qmhl.toolposition.base.BaseActivity
import com.qmhl.toolposition.databinding.ActivityCodeLoginBinding
import com.qmhl.toolposition.utils.PUtils
import com.qmhl.toolposition.utils.PreferenceUtil
import com.qmhl.toolposition.utils.RegexUtil
import com.umeng.sms.UMSMS
import com.umeng.sms.listener.UMSMSCodeListener
import kotlinx.coroutines.launch


/**
 * @author: lqhl
 * @createTime: 2023-11-03  17:10
 * @description: 验证码登录
 */
class VerifiCodeLoginActivity : BaseActivity() {

    private lateinit var binding: ActivityCodeLoginBinding
    private var smsTime: Int = 60;


    var countDownTimer = object : CountDownTimer((smsTime * 1000).toLong(), 1000) {
        //1000ms运行一次onTick里面的方法
        override fun onFinish() {

        }


        override fun onTick(millisUntilFinished: Long) {

            val value = smsTime--

            binding.tvGetSmsCode.text = smsTime.toString()
            if (smsTime == 0) {
                smsTime = 60
                binding.tvGetSmsCode.text = "获取验证码"
                binding.tvGetSmsCode.paint.flags = Paint.UNDERLINE_TEXT_FLAG
            }


        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCodeLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)


    }


    override fun initData() {
        super.initData()

        //设置下划线
        binding.tvGetSmsCode.paint.flags = Paint.UNDERLINE_TEXT_FLAG

        /*   val sb = StringBuilder().run {
               append("<font color=\"#333333\">我已阅读并同意</font>")
               append("<font color=\"#01cb9b\">《用户协议》</font>")
               append("<font color=\"#333333\">和</font>")
               append("<font color=\"#01cb9b\">《隐私协议》</font>")
               toString()
           }

           binding.tvLoginAgreement.text = Html.fromHtml(sb)*/
        binding.tvLoginAgreement.text = getClickableSpan()
        binding.tvLoginAgreement.movementMethod = LinkMovementMethod.getInstance();
    }


    private fun getClickableSpan(): SpannableString? {
        val spannableString =
            SpannableString("我已阅读并同意《用户协议》和《隐私协议》")
        val clickableSpan1: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startAgreementActivity(
                    PUtils.Config.userAgreement_title,
                    PUtils.Config.userAgreement_assert
                )
            }

            //重写该方法去掉下划线
            override fun updateDrawState(ds: TextPaint) {
                ds.isUnderlineText = false
            }
        }
        val clickableSpan2: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startAgreementActivity(
                    PUtils.Config.privacyAgreement_title,
                    PUtils.Config.privacyAgreement_assert
                )
            }

            //重写该方法去掉下划线
            override fun updateDrawState(ds: TextPaint) {
                ds.isUnderlineText = false
            }
        }

        //设置文字的点击事件
        spannableString.setSpan(clickableSpan1, 7, 12, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(clickableSpan2, 14, 19, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)

        //设置文字的前景色
        spannableString.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.agreementText)),
            7,
            12,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        spannableString.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.agreementText)),
            14,
            19,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        return spannableString
    }


    private fun startAgreementActivity(title: String, url: String) {

        goWebView(title, url)

    }

    private fun goWebView(title: String, url: String) {
        val intent = Intent(OneKeyLoginActivity@ this, AgreementActivity::class.java)
        intent.putExtra("title", title)
        intent.putExtra("url", url)
        startActivity(intent)
    }


    override fun initListener() {
        super.initListener()
        binding.ivBack.setOnClickListener {
            finish()
        }
        binding.btnLogin.setOnClickListener { codeLogin() }
        binding.tvGetSmsCode.setOnClickListener {
            val length = binding.tvGetSmsCode.text.length
            if (length < 5) {
                //还在倒计时
            } else {
                //准备倒计时
                val phoneNumber = binding.etAccount.text.toString()
                var isPhone = RegexUtil.regexPhone(phoneNumber)
                if (!isPhone) {
                    Toaster.showShort(PUtils.Toast.PLEASE_INPUT_PHONE)

                } else {
                    binding.tvGetSmsCode.paint.flags = 0
                    countDownTimer.start()
                    getSmsCode()
                }

            }


        }
    }

    private fun getSmsCode() {
        val phoneNumber = binding.etAccount.text.toString()
//        UMSMS.getVerificationCode(phoneNumber, "SMS_464051148" +
//                "", object : UMSMSCodeListener {
//            override fun getCodeSuccess(code: String?) {
//                println(code)
//            }
//
//            override fun getCodeFailed(resultCode: Int, p1: String?) {
//                Toaster.showShort(p1)
//            }
//        })
        lifecycleScope.launch {
            var content = UserService.create()
                .getSmsCode(phoneNumber)
            if (content.code == 200) {

                Toaster.showShort(PUtils.Toast.GET_SMS_SUCCESS)
            } else {
                Toaster.showShort(content.msg)
            }
        }
    }

    private fun codeLogin() {

        val isCheck = binding.cbCode.isChecked
        if (!isCheck) {
            Toaster.showShort(PUtils.Toast.SEE_AGREEMENT_AND_LOGIN)
            return
        }

        var account = binding.etAccount.text.toString()
        var code = binding.etCode.text.toString()


        var isPhone = RegexUtil.regexPhone(account)
        if (!isPhone) {
            Toaster.showShort(PUtils.Toast.PLEASE_INPUT_PHONE)
            return
        }
        if (code.isEmpty()) {
            Toaster.showShort(PUtils.Toast.PLEASE_INPUT_CODE)
            return
        }

        lifecycleScope.launch {
            var content = UserService.create()
                .codeLogin(account, code)
            if (content.code == 200) {
                Toaster.showShort(PUtils.Toast.LOGIN_SUCCESS)
                PreferenceUtil.saveCurrentUser(content.data.phone, content.data.token)
                startMainActivity()
            } else {
                Toaster.showShort(content.msg)
            }
        }


    }

    fun startMainActivity() {
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

}